package com.ease.platform.usercontext.util;

import java.util.List;

import com.ease.common.util.Detect;
import com.ease.dao.util.DataAccessObjectUtil;
import com.ease.platform.model.type.IdentityGroup;
import com.ease.platform.usercontext.vo.UserContext;

public abstract class UserContextUtil extends Detect {

	public static final String LOCATIONCONSTRAINTSQLFRAGMENT = "ID IN (SELECT ID FROM C_LOCATION R CONNECT BY NOCYCLE PRIOR R.ID=R.PARENTLOCATION_ID START WITH ID IN (?) "
			+ "UNION ALL SELECT ID FROM C_LOCATION R CONNECT BY NOCYCLE R.ID= PRIOR R.PARENTLOCATION_ID START WITH ID IN (?))";

	// 为性能考虑 子查询里拼入entitysql
	public static final String LOCATIONCONSTRAINTSQLFRAGMENTWITHENTITYTYPE = "ID IN (SELECT ID FROM C_LOCATION R WHERE R.ENTITYTYPE_ID = ? CONNECT BY NOCYCLE PRIOR R.ID=R.PARENTLOCATION_ID START WITH ID IN (?) "
			+ "UNION ALL SELECT ID FROM C_LOCATION R WHERE R.ENTITYTYPE_ID = ? CONNECT BY NOCYCLE R.ID= PRIOR R.PARENTLOCATION_ID START WITH ID IN (?))";

	public static void copy(UserContext target, UserContext source) {
		if (null != target && null != source) {
			target.setGuid(source.getGuid());
			target.setOperator(source.getOperator());
			target.setUser(source.getUser());
			target.setGroups(target.getGroups());
			target.setMaintenanceLocations(source.getMaintenanceLocations());
		}
	}

	public static long[] groupIds(UserContext userContext) {
		if (null != userContext) {
			return DataAccessObjectUtil.idOf(userContext.getGroups());
		}
		return null;
	}

	public static boolean hasGroup(String groupCode, UserContext userContext) {
		List<IdentityGroup> groups = userContext.getGroups();

		if (null != groups) {
			for (IdentityGroup group : groups) {
				if (groupCode.equals(group.getCode())) {
					return true;
				}
			}
		}
		return false;
	}

	/* no param */
	public static boolean isAdministrator(UserContext userContext) {
		return hasGroup(IdentityGroup.Administrators, userContext);
	}

	public static boolean isManager(UserContext userContext) {
		return hasGroup(IdentityGroup.Managers, userContext);
	}

	public static boolean isSpectialCodeDegree(UserContext userContext) {
		return hasGroup(IdentityGroup.SPECTIALCODEDEGREES, userContext);
	}

	public static boolean isProvinceAdmin() {
		return hasGroup(IdentityGroup.provinceAdmin, UserContextThreadLocal.getUserContext());
	}

	public static boolean isNetworkConstruction() {
		return hasGroup(IdentityGroup.networkConstruction, UserContextThreadLocal.getUserContext());
	}

	public static boolean isNetworkConstructionAdmin() {
		return hasGroup(IdentityGroup.networkConstructionAdmin, UserContextThreadLocal.getUserContext());
	}

	public static boolean isConstructors() {
		return hasGroup(IdentityGroup.Constructors, UserContextThreadLocal.getUserContext());
	}

	public static boolean isNocAdmin() {
		return hasGroup(IdentityGroup.nocAdmin, UserContextThreadLocal.getUserContext());
	}

}
